﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using Dez;
using DispatcherWebAppModel;

public partial class Account_Logon : System.Web.UI.Page
{
    DEZ context = new DEZ();
    DispatcherWebAppEntities dispEntities = new DispatcherWebAppEntities();
    HttpCookie obj_cookie;
    string pswd;

    protected void Page_Load(object sender, EventArgs e)
    {
        PrepareCombobox();
        if (!IsPostBack && !IsCallback)
        {
            //read cookie
            obj_cookie = Request.Cookies["UserInfo"];
            if (obj_cookie != null)
            {
                cbb_fio.SelectedItem = cbb_fio.Items.FindByValue(Convert.ToInt32(obj_cookie.Values["ActiveUser"]));
                OpenKontragent(Convert.ToInt32(cbb_fio.Value));
                cbb_kontr.SelectedItem = cbb_kontr.Items.FindByValue(Convert.ToInt32(obj_cookie.Values["ActiveKontragent"]));
                tbPassword.Focus();
            }
        }
    }
    protected void cbb_fio_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (cbb_fio.Value != null)
        {
            //загружаем список контрагентов
            cbb_kontr.Value = null;
            OpenKontragent(Convert.ToInt32(cbb_fio.Value));
            cbb_kontr.Focus();
        }
    }

    protected void PrepareCombobox()
    {
        cbb_fio.ValueField = "CODE";
        cbb_fio.AutoPostBack = true;
        //
        string cs = context.Connection.ConnectionString;
        var query = from p in context.PIPLE
                    select new { p.CODE, FIO = p.F + " " + p.I + " " + p.O };
        cbb_fio.DataSource = query.ToArray();
        cbb_fio.DataBind();

        if (cbb_fio.Value != null)
        {
            int kontr = Convert.ToInt32(cbb_fio.Value);
            OpenKontragent(kontr);
        }
        else
            cbb_kontr.Value = null;
    }

    private void OpenKontragent(int code)
    {
        //cbb_kontr.Columns.Clear();
        //cbb_kontr.Columns.Add(new DevExpress.Web.ASPxEditors.ListBoxColumn("KONTRAGENT"));
        //cbb_kontr.Columns.Add(new DevExpress.Web.ASPxEditors.ListBoxColumn("NAME"));
        //cbb_kontr.Columns.Add(new DevExpress.Web.ASPxEditors.ListBoxColumn("PSWD"));
        //cbb_kontr.AutoPostBack = true;
        //cbb_kontr.EnableCallbackMode = true;
        //cbb_kontr.IncrementalFilteringMode = DevExpress.Web.ASPxEditors.IncrementalFilteringMode.StartsWith;
        //
        var query = from w in context.WORKER
                    where w.PIPLE == code
                    join p in context.PIPLE on w.PIPLE equals p.CODE
                    join k in context.KONTRAGENT on w.KONTRAGENT equals k.CODE
                    select new { w.KONTRAGENT, k.NAME, PSWD = w.USERNAME };
        cbb_kontr.DataSource = query.ToArray();

        cbb_kontr.ValueField = "KONTRAGENT";
        cbb_kontr.TextField = "NAME";
        cbb_kontr.DataBind();
        //устанавливаем на первую запись
        if (IsCallback)
        { cbb_kontr.SelectedIndex = 0; }


    }
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        if (cbb_fio.Value != null)
        {
            //получаем правильный пароль
            GetPSWD(Convert.ToInt32(cbb_fio.Value));

            if (pswd == tbPassword.Text)
            {
                //if (Membership.ValidateUser(tbUserName.Text, tbPassword.Text)) {
                /*if (string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))
                {
                    FormsAuthentication.SetAuthCookie(cbb_fio.Text, false);
                    Response.Redirect("~/");
                }
                else
                {*/
                FormsAuthentication.RedirectFromLoginPage(cbb_fio.Text, false);
                //}
                Saveprofile();
            }
            else
            {
                tbPassword.ErrorText = "Неверный пароль!";
                tbPassword.IsValid = false;
                //tbUserName.ErrorText = "Invalid user";
                //tbUserName.IsValid = false;
            }
        }
    }

    private void GetPSWD(int code)
    {
        var query = (from p in context.PIPLE
                     where p.CODE == code
                     select p).First();
        pswd = query.PSWD;
    }

    private void Saveprofile()
    {
        int code = Convert.ToInt32(cbb_kontr.Value);
        int PipleCode = Convert.ToInt32(cbb_fio.Value);
        var query = (from k in context.KONTRAGENT
                     where k.CODE == code
                     select k).First();

        var UserQuery = (from w in context.WORKER
                         where w.KONTRAGENT == code || w.PIPLE == PipleCode
                         select w).First();

        Profile.Initialize(cbb_fio.Text, true);
        Profile.UserInfo.ActiveKontragent = Convert.ToInt32(cbb_kontr.Value);
        Profile.UserInfo.ActiveUser = UserQuery.CODE;
        Profile.UserInfo.PeopleCode = Convert.ToInt32(cbb_fio.Value);
        Profile.UserInfo.KontragentType = query.KTYPE;
        Profile.UserInfo.KontrName = query.FULLNAME;
        Profile.UserInfo.UserFIO = cbb_fio.Text;

        if (query.DISP_ID != null)
        {
            Profile.UserInfo.disp.Kontragent = query.DISP_ID.Value;
        }
        else { Profile.UserInfo.disp.Kontragent = -1; }
        var dispQuery = (from p in context.PIPLE
                         where p.CODE == PipleCode
                         select p).First();

        Profile.UserInfo.disp.Login = dispQuery.DISP_LOGIN;
        Profile.UserInfo.disp.Pass = dispQuery.DISP_PSWD;

        var DispUser = (from u in dispEntities.App_User
                        where u.Password == dispQuery.DISP_PSWD || u.UserName == dispQuery.DISP_LOGIN
                     select u).FirstOrDefault();
        if (DispUser!= null)
        {
            Profile.UserInfo.disp.UserId = DispUser.UserId;
        }
        //Session["UserInfo"] = usrinfo;

        //сессия
        /*Session["ActiveKontragent"] = cbb_kontr.Value;
        Session["ActiveUser"] = cbb_fio.Value;*/

        //создаем временный набор Cookie который будет доступен пока браузер не закрыли
        HttpCookie theCookie = new HttpCookie("UserInfo");
        theCookie["ActiveKontragent"] = cbb_kontr.Value.ToString();
        theCookie["ActiveUser"] = cbb_fio.Value.ToString();
        Response.Cookies.Add(theCookie);
    }

}